/*
 * !! Workers should never stop on Exceptions.
 * !! Do not System.exit(1) on file reading exception. Throw an exception.
 */
package workerGraphMakers;

import static java.lang.System.err;
import static java.lang.System.exit;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import system.Combiner;
import system.FileSystem;
import system.GraphMaker;
import system.Vertex;
import system.Worker;
import system.WorkerJob;

/**
 *
 * @author Pete Cappello
 */
public class StandardWorkerGraphMaker implements GraphMaker
{
    public int makeGraph( Worker worker ) 
    {
        int workerNum       = worker.getWorkerNum();
        WorkerJob workerJob = worker.getWorkerJob();
        FileSystem fileSystem = workerJob.getFileSystem();
        Combiner combiner     = workerJob.getCombiner();
        Vertex vertexFactory  = workerJob.getVertexFactory();
        int numVertices = 0;
        try
        {
            // read file
            FileInputStream fileInputStream = fileSystem.getWorkerInputFileInputStream( workerNum );
            DataInputStream dataInputStream = new DataInputStream( fileInputStream );
            BufferedReader bufferedReader   = new BufferedReader(new InputStreamReader( dataInputStream ));
            for ( String line; ( line = bufferedReader.readLine() ) != null; numVertices++ )
            {
                Vertex vertex = vertexFactory.make( line, combiner );
                worker.addVertex( vertex, workerJob.getPartId( vertex ) );
            }
            dataInputStream.close();
        }
        catch ( Exception exception )
        {
            err.println( "SimpleWorkerGraphMaker.makeGraph: Error: " + exception.getMessage());
            exception.printStackTrace();
            exit( 1 );
        }
        return numVertices;
    }
}
